package com.water.tao.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TencentStockFetcher {

    private static final Logger logger = LoggerFactory.getLogger(TencentStockFetcher.class);

    // 腾讯证券获取沪深全部股票列表的接口 (此接口可能随时间变化而失效)
    private static final String TENCENT_STOCK_LIST_API = "https://proxy.finance.qq.com/cgi-bin/sinaguguo/search_info?_type=all&_search=stock&type=sh_sz&count=20000&order=code&asc=1&random=";

    public static void main(String[] args) {
        try {
            logger.info("开始从腾讯证券抓取 A 股股票列表...");
            List<TStock> stocks = getAStockListFromTencent();
            if (!stocks.isEmpty()) {
                logger.info("成功获取 {} 只 A 股股票列表。", stocks.size());
                // 打印前10只股票信息作为示例
                for (int i = 0; i < Math.min(10, stocks.size()); i++) {
                    TStock stock = stocks.get(i);
                    logger.info("股票信息 - 代码: {}, 名称: {}, 市场: {}", stock.getCode(), stock.getName(), stock.getMarket());
                }
            } else {
                logger.warn("未能从腾讯证券抓取到股票列表或列表为空。");
            }

            // 打印连接池统计信息
            logger.info("HttpClient Connection Pool Stats (after fetching stocks): {}", HttpClientUtil.getConnectionPoolStats());

        } catch (IOException | ParseException e) {
            logger.error("获取股票列表时发生 IO/解析错误: {}", e.getMessage(), e);
        } catch (Exception e) {
            logger.error("获取股票列表时发生未知错误: {}", e.getMessage(), e);
        }
    }

    public static List<TStock> getAStockListFromTencent() throws IOException, ParseException {
        // 构建带随机数的完整 URL，避免缓存
        String requestUrl = TENCENT_STOCK_LIST_API + Math.random();
        logger.debug("请求腾讯证券 API URL: {}", requestUrl);

        CloseableHttpClient httpClient = HttpClientUtil.getHttpClient();
        HttpGet httpGet = new HttpGet(requestUrl);

        // 模拟浏览器User-Agent，避免被服务器识别为爬虫并拒绝
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
        httpGet.setHeader("Accept", "application/json, text/plain, */*");
        httpGet.setHeader("Referer", "https://stockapp.finance.qq.com/"); // 模拟从腾讯证券页面跳转

        List<TStock> stocks = new ArrayList<>();
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getCode();
            String responseBody = EntityUtils.toString(response.getEntity());

            if (statusCode == 200) {
                logger.debug("腾讯证券 API 返回数据 (部分): {}", responseBody.substring(0, Math.min(responseBody.length(), 500)) + "..."); // 避免打印超长字符串
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(responseBody);

                JsonNode dataNode = rootNode.get("data");
                if (dataNode != null && dataNode.isObject()) {
                    JsonNode listNode = dataNode.get("list");
                    if (listNode != null && listNode.isArray()) {
                        for (JsonNode stockNode : listNode) {
                            String id = stockNode.get("id").asText(); // 例如 "sh600000"
                            String code = stockNode.get("code").asText(); // 例如 "600000"
                            String name = stockNode.get("name").asText(); // 例如 "浦发银行"
                            String market = stockNode.get("market").asText(); // 例如 "SH"

                            // 简单过滤：确保获取到有效的股票代码和名称
                            if (code != null && !code.isEmpty() && name != null && !name.isEmpty()) {
                                stocks.add(new TStock(code, name, market));
                            } else {
                                logger.warn("跳过无效股票数据: {}", stockNode.toString());
                            }
                        }
                    } else {
                        logger.warn("JSON 'data.list' 节点不存在或不是数组。");
                    }
                    JsonNode countNode = dataNode.get("count");
                    if (countNode != null) {
                        logger.info("腾讯证券 API 报告总股票数量: {}", countNode.asInt());
                    }
                } else {
                    logger.warn("JSON 'data' 节点不存在或不是对象。");
                }
            } else {
                logger.error("腾讯证券 API 请求失败，状态码: {}，响应体: {}", statusCode, responseBody);
                throw new IOException("Failed to fetch stock list from Tencent API. Status: " + statusCode);
            }
        }
        return stocks;
    }
}

// 简单的股票数据模型（保持不变）
class TStock {
    private String code;
    private String name;
    private String market; // 例如: "SH" (上海), "SZ" (深圳)

    public TStock(String code, String name, String market) {
        this.code = code;
        this.name = name;
        this.market = market;
    }

    public String getCode() {
        return code;
    }

    public String getName() {
        return name;
    }

    public String getMarket() {
        return market;
    }

    @Override
    public String toString() {
        return "Stock{" +
                "code='" + code + '\'' +
                ", name='" + name + '\'' +
                ", market='" + market + '\'' +
                '}';
    }
}
